package com.youka.bussiness.common.utils;

import org.apache.commons.lang.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * session上下文
 */
public class SessionContext {

    private static final ThreadLocal<Map<String, String>> threadLocalToken = new ThreadLocal<>();

    /**
     * 获取当前用户AccessToken
     */
    public static String getCurrentToken(String token) {
        String item = getCurrentThreadContext().get(token);
        if (StringUtils.isBlank(item)) {
//            UserTokenMapper userTokenMapper = SpringContextUtils.getBean(UserTokenMapper.class);
//            UserToken userToken = userTokenMapper.selectOne(new QueryWrapper<UserToken>().lambda().eq(UserToken::getToken, token));
//            if (userToken == null) {
//                throw new BaseException("250", "重新登录");
//            }
//            item = userToken.getId();
            setCurrentToken(token, item);
        }
        return item;
    }


    private static Map<String, String> getCurrentThreadContext() {
        Object currentcontext = threadLocalToken.get();
        if (currentcontext == null) {
            currentcontext = new HashMap();
            threadLocalToken.set((Map<String, String>) currentcontext);
        }
        return (Map) currentcontext;
    }

    /**
     * 设置当前用户accessToken到session上下文
     *
     * @param token
     */
    public static void setCurrentToken(String token, String userId) {
        Map<String, String> map = new HashMap<>();
        map.put(token, userId);
        getCurrentThreadContext().put(token, userId);
    }

    public static Object remove(String name) {
        Map currentThreadContext = getCurrentThreadContext();
        Object o = currentThreadContext.remove(name);
        if (currentThreadContext.isEmpty()) {
            clear();
        }
        return o;
    }

    /**
     * 获取线程上下文
     *
     * @return
     */
    public static String getUser() {
        return getCurrentToken("token");
    }


    public static void clear() {
        getCurrentThreadContext().clear();
        threadLocalToken.set(null);
    }


    /**
     * 清除token
     */
    public static void clearContext() {
        threadLocalToken.remove();
    }

}
